// 分类筛选功能
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    checkAuthStatus();

    // 登出功能
    document.querySelector('.exit').addEventListener('click', function() {
        if(confirm('确定要退出登录吗？')) {
            logout();
        }
    });

    const filterButtons = document.querySelectorAll('.filter-btn');
    const aiCards = document.querySelectorAll('.ai-card');
    const container = document.querySelector('.ai-tools-container');

    // 筛选功能
    filterButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 更新按钮状态
            filterButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');

            const category = this.getAttribute('data-category');

            // 添加筛选动画
            container.style.opacity = '0.5';
            container.style.transform = 'scale(0.98)';

            setTimeout(() => {
                // 筛选卡片
                aiCards.forEach((card, index) => {
                    if (category === 'all') {
                        card.style.display = 'block';
                        card.style.animationDelay = `${index * 0.1}s`;
                        card.classList.add('fade-in');
                    } else {
                        const categories = card.getAttribute('data-categories').split(',');
                        if (categories.includes(category)) {
                            card.style.display = 'block';
                            card.style.animationDelay = `${index * 0.1}s`;
                            card.classList.add('fade-in');
                        } else {
                            card.style.display = 'none';
                            card.classList.remove('fade-in');
                        }
                    }
                });

                // 恢复容器样式
                container.style.opacity = '1';
                container.style.transform = 'scale(1)';
            }, 300);
        });
    });

    // 卡片悬停效果
    aiCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-10px) scale(1.02)';
            this.style.boxShadow = '0 20px 40px rgba(0,0,0,0.15)';
        });

        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
            this.style.boxShadow = '0 8px 20px rgba(0,0,0,0.08)';
        });
    });

    // 标签悬停效果
    const tags = document.querySelectorAll('.tag');
    tags.forEach(tag => {
        tag.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px) scale(1.05)';
        });

        tag.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
        });
    });

    // 初始显示所有卡片
    aiCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(30px)';
        card.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
        card.style.animationDelay = `${index * 0.1}s`;

        setTimeout(() => {
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, 100 + index * 100);
    });

    // 添加CSS动画
    const style = document.createElement('style');
    style.textContent = `
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .fade-in {
            animation: fadeIn 0.6s ease forwards;
        }

        .ai-tools-container {
            transition: opacity 0.3s ease, transform 0.3s ease;
        }

        .ai-card {
            transition: all 0.3s ease;
        }

        .tag {
            transition: all 0.3s ease;
        }
    `;
    document.head.appendChild(style);
});

function checkAuthStatus() {
    fetch('/api/check_auth', {
        credentials: 'include'
    })
    .then(response => response.json())
    .then(data => {
        if (!data.logged_in) {
            window.location.href = '/login';
        } else {
            const userInfo = document.getElementById('userInfo');
            const usernameDisplay = document.getElementById('usernameDisplay');
            if (userInfo && usernameDisplay) {
                userInfo.style.display = 'flex';
                usernameDisplay.textContent = data.username;
            }
        }
    })
    .catch(error => {
        console.error('检查登录状态失败:', error);
        window.location.href = '/login';
    });
}

async function logout() {
    try {
        // 新增：退出登录前发送 client_disconnect 类型的UDP消息
        const userInfoResp = await fetch('/api/check_auth', { credentials: 'include' });
        const userInfo = await userInfoResp.json();
        if (userInfo.logged_in) {
            await fetch('/api/udp-proxy', {
                method: 'POST',
                credentials: 'include',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    message: {
                        type: 'client_disconnect',
                        data: {
                            user_id: userInfo.user_id,
                            username: userInfo.username,
                            timestamp: new Date().toISOString()
                        }
                    }
                })
            });
        }
        const response = await fetch('/api/logout', {
            method: 'POST',
            credentials: 'include'
        });
        const data = await response.json();
        if (data.redirect) {
            window.location.href = data.redirect;
        }
    } catch (error) {
        console.error('退出登录错误:', error);
        window.location.href = '/login';
    }
}
